package com.buba.system.controller;

import com.buba.system.pojo.SystemUser;
import com.buba.system.service.LoginService;
import com.buba.system.service.MenuService;
import com.buba.system.service.RoleService;
import com.buba.util.GenerateKey;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.IncorrectCredentialsException;
import org.apache.shiro.authc.LockedAccountException;
import org.apache.shiro.authc.UnknownAccountException;
import org.apache.shiro.authc.UsernamePasswordToken;
import org.apache.shiro.authz.annotation.RequiresRoles;
import org.apache.shiro.crypto.hash.SimpleHash;
import org.apache.shiro.subject.Subject;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.servlet.ModelAndView;

import java.util.HashMap;
import java.util.Map;

/**
 * 登录
 */
@RestController
@RequestMapping("/UserController")
public class LoginController {
    private LoginService loginService;//登录
    private RoleService roleService;//角色
    private MenuService menuService;//菜单



    /**
     * 登录功能
     * @param systemUser
     * @return
     */
    @RequestMapping("/login")
    public Map<String,Object> login(SystemUser systemUser){
        Map<String,Object> map = new HashMap<>();
        Subject subject = SecurityUtils.getSubject();//subject主体
        try {  //isAuthenticated 认证状态(认证是否成功) ture或false
            if (!subject.isAuthenticated()) {
                // 创建帐号密码 令牌
                UsernamePasswordToken token = new UsernamePasswordToken(systemUser.getUserName(), systemUser.getUserPassword());
                // 通过subject.login()进行登录认证
                subject.login(token);
            }
            map.put("message", "登录成功");
        } catch (UnknownAccountException uae) {
            map.put("message", "帐号不存在");
        } catch (IncorrectCredentialsException ice) {
            map.put("message", "密码错误");
        } catch (LockedAccountException lae) {
            // 该用户名的帐户被锁定，无法登录。给他们一个信息?
        }
        return map;
    }

    /**
     * 注册功能
     * @param map
     * @return
     */
    @RequestMapping("/register")
    public Map<String,Object> register(@RequestParam Map<String,Object> map){
        //指定格式开头加上当前的事件作为id 调用时间戳类
        String userId = GenerateKey.getKey("S");
        map.put("userId",userId);

        // shiro 加密 （算法名字，原始密码，盐，散列次数）
        SimpleHash userPassword = new SimpleHash("MD5", map.get("userPassword"), "a", 1);
        //toHex()字符串转码，字符串转换为十六进制编码
        map.put("userPassword",userPassword.toHex());

        //添加注册信息
        Integer count = loginService.register(map);
        if(count ==1){
            map.put("message","注册成功");
        }
        return map;
    }

    /**
     * 退出用户登录
     * 并清除登录缓存信息
     * @return
     */
    @RequestMapping("/logout")
    public ModelAndView logout(){
        Subject subject = SecurityUtils.getSubject();
        subject.logout();//退出用户登录
        return new ModelAndView("login.html");
    }


    @Autowired
    @Qualifier("loginServiceImpl")
    public void setLoginService(LoginService loginService) {
        this.loginService = loginService;
    }

    @Autowired
    @Qualifier("roleServiceImpl")
    public void setRoleService(RoleService roleService) {
        this.roleService = roleService;
    }

    @Autowired
    @Qualifier("menuServiceImpl")
    public void setMenuService(MenuService menuService) {
        this.menuService = menuService;
    }
}
